Skip to content

fix(json): produce valid JSON when lines=False spans multiple batches (#7037)#8317

Open
sridhar-3009 wants to merge 2 commits into
huggingface:mainfrom
sridhar-3009:fix/7037-to-json-lines-false
Open

fix(json): produce valid JSON when lines=False spans multiple batches (#7037)#8317
sridhar-3009 wants to merge 2 commits into
huggingface:mainfrom
sridhar-3009:fix/7037-to-json-lines-false

Conversation

@sridhar-3009

Copy link
Copy Markdown

Summary

Fixes #7037.

Dataset.to_json(lines=False) raised NotImplementedError (and before the guard was added, silently produced invalid JSON) whenever batch_size < num_rows — i.e., the default case for any dataset larger than DEFAULT_MAX_BATCH_SIZE (1000 rows).

Root cause: Each batch was serialised to its own JSON array ([{...}, ...]) and written back-to-back in the file, producing e.g. [{...}][{...}] — syntactically invalid.

Fix (two changes in src/datasets/io/json.py):

  1. write() — Narrow the NotImplementedError guard to dict-producing orientations (split, index, columns, table) only. Array-producing orientations (records, values) can now be batched safely.

  2. _write() — When lines=False and orient in ("records", "values"), strip the outer [ / ] from each batch's bytes and emit a single wrapping [...], streaming with no extra memory overhead. Dict-producing orientations fall through to the unchanged write-as-is path.

As a bonus, the single-proc and multiprocessing iteration loops are unified via contextlib.nullcontext, removing ~10 lines of duplication.

Verified:

import io, json
from datasets import Dataset
from datasets.io.json import JsonDatasetWriter

ds = Dataset.from_dict({"id": list(range(25)), "value": [f"v{i}" for i in range(25)]})
buf = io.BytesIO()
JsonDatasetWriter(ds, buf, batch_size=10, lines=False).write()  # 3 batches
buf.seek(0)
result = json.loads(buf.read())   # previously raised NotImplementedError / produced invalid JSON
assert len(result) == 25          # single valid JSON array with all rows

Test plan

  • New parametrised test test_dataset_to_json_lines_false_batched covers orient="records" and orient="values" with batch_size < num_rows
  • Full TestJsonDatasetWriter suite passes (20 tests; 3 pre-existing errors for shared_datadir fixture from missing pytest-datadir plugin, unrelated to this change)

Sai Sridhar added 2 commits July 10, 2026 09:45
`add_column` delegates to `map` but never updates the returned dataset's
features schema. Calling `add_column` on a typed IterableDataset silently
drops the `features` attribute (returns `None`), breaking any code that
inspects schema after the operation.

Follow the same pattern as `rename_columns`: save the existing features
before the map call, infer the new column's type from the column data via
PyArrow, then write the merged Features back to `_info.features`.

Fixes huggingface#5752.
…iple batches

When `lines=False` and `batch_size < num_rows`, each batch was written
as its own JSON array (`[{...}]`), producing concatenated arrays that
are invalid JSON. The code guarded this with a `NotImplementedError`
for all orientations.

Fix: lift the error for array-producing orientations (`records`,
`values`) and merge batches in `_write` by stripping the outer `[`/`]`
from each batch's bytes and emitting a single wrapping `[...]`.
Dict-producing orientations (`split`, `index`, `columns`, `table`)
still raise `NotImplementedError` when `batch_size < num_rows` since
their output cannot be meaningfully merged across batches.

Also refactors `_write` to share a single iteration loop between the
single-proc and multiprocessing paths via `contextlib.nullcontext`.

Fixes huggingface#7037
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A bug of Dataset.to_json() function

1 participant